package json;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import fj.F;
import fj.F2;
import fj.data.List;
import fj.data.Option;

public class JSONHelpers {

	
	public static F<JSONObject,fj.data.List<String>> getList = new F<JSONObject,fj.data.List<String>>()
	{

		@Override
		public List<String> f(JSONObject arg0) {
			fj.data.List<String> list = List.list();
			for(Iterator<String> i = arg0.keys();i.hasNext();)
			{
				try {
					String key = i.next();
					if(arg0.get(key) instanceof String)
						list = list.cons((String) arg0.get(key));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
			return list;
		}
		
	};


	public static F<JSONArray,fj.data.List> getListFromArray = new F<JSONArray,fj.data.List>()
	{

		@Override
		public List<JSONObject> f(JSONArray array) {
			fj.data.List<JSONObject> list = List.list();
			for(int i = 0;i<array.length();i++)
			{
				try {
					if(array.get(i) instanceof JSONObject)
						list = list.cons((JSONObject) array.get(i));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			return list;
		}
		
	};


	public static F2<JSONObject,String,String> getSome = new F2<JSONObject,String,String>()
	{

		@Override
		public String f(JSONObject obj, String key) {
			if(obj.has(key))
				try {
					return Option.fromNull(obj.getString(key)).orSome("");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return "";
		}
		
	};



}
